var CmsAjaxTabControl = Class.create(BaseControl, {
    tabs: null,
    query: null,
    tabContainer: null,
    hashKey: null,
	tabId: null,

    observeEvent: function()
    {
        this.tabs = this.find('.tabItem');
        this.query = this.view.getAttribute('query');
        this.tabContainer = $('tabContainer');
        this.hashKey = 'tab';
        var me = this;
        this.find('.tabHandler').invoke('observe', 'click', function(){
            var tabId = this.getAttribute('tabId');
            me.setHash(me.hashKey, tabId);
        });
        this.observeHashChange();
    },

    onHashChange: function(newHash)
    {
        var tabId = this.getHash(this.hashKey, newHash);
		if (this.tabId != tabId)
		{
			if (!tabId) tabId = this.tabs.first().getAttribute('tabId');
			this.selectTab(tabId);
		}
    },

    loadTabContent: function(url)
    {
        if (!url) throw 'Tab url is empty';
        var me = this;
        Client.ajax(url, {
            parameters: this.query,
            onComplete: function(response){
                var div = new Element('div', {'id':'tabContent_'+me.tabId, 'class':'tabContent'});
                me.tabContainer.insert(div.update(response));
            }
        });
    },

    selectTab: function(tabId)
    {
		this.tabId = tabId;
        var tab = $('tab_'+tabId);
        this.find('.dvtSelectedCell').invoke('removeClassName', 'dvtSelectedCell');
        this.find('.dvtSelectedCellBottom').invoke('removeClassName', 'dvtSelectedCellBottom');
        tab.addClassName('dvtSelectedCell');
        
        var tabBottom = $('tabBottom_'+tabId);
        if (tabBottom)
            tabBottom.addClassName('dvtSelectedCellBottom');

        this.find('.tabContent').invoke('hide');
        var content = $('tabContent_'+this.tabId);
        if (content) content.show();
        else
        {
            var url = tab.getAttribute('url');
            this.loadTabContent(url);
        }
    }
});